package cn.itsource.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.utils.BaiduAiUtils;
import cn.itsource.basic.utils.PageResult;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.Shop;
import cn.itsource.org.domain.ShopAuditLog;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.mapper.ShopAuditLogMapper;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.query.ShopQuery;
import cn.itsource.org.service.ShopService;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.mapper.LogininfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public List<Shop> findAll() {
        return shopMapper.findAll();
    }

    @Override
    public Shop findOne(Long id) {
        return shopMapper.findOne(id);
    }

    @Transactional
    @Override
    public void add(Shop shop) {
        shopMapper.add(shop);
    }

    @Transactional
    @Override
    public void update(Shop shop) {

        shopMapper.update(shop);
    }

    @Transactional
    @Override
    public void delete(Long id) {
        shopMapper.delete(id);
    }

    @Transactional
    @Override
    public void patchdel(Long[] ids) {
        shopMapper.patchdel(ids);
    }

    @Override
    public PageResult<Shop> queryPage(ShopQuery shopQuery) {
        Integer totals = shopMapper.queryCount(shopQuery);
        List<Shop> list = shopMapper.queryData(shopQuery);
        return new PageResult<Shop>(totals,list);
    }

    @Override
    public AjaxResult settlement(Shop shop) {
        //1.校验空值
        if (StrUtil.isBlank(shop.getName()) || StrUtil.isBlank(shop.getTel()) ||
        StrUtil.isBlank(shop.getAddress())){
            throw new BusinessException("信息不能为空！！！");
        }
        //2.校验两次密码
        if (!shop.getAdmin().getPassword().equals(shop.getAdmin().getComfirmPassword())){
            throw new BusinessException("两次密码！！！");
        }
        //3.校验店铺在本地是否存在
        Shop shopOne = shopMapper.findNameandAddress(shop);
        if (shopOne != null){
            throw new BusinessException("店铺在本地以存在！！！");
        }

        //4.百度智能审核店铺名称
        if (!BaiduAiUtils.textCensor(shop.getName())){
            throw new BusinessException("不好意思，您店铺名称以违规！！！");
        }

        //5.百度智能审核店铺图片
        if (!StrUtil.isBlank(shop.getLogo())){
            if (!BaiduAiUtils.imgCensor(shop.getLogo())){
                throw new BusinessException("不好意思，您店铺logo以违规！！！");
            }
        }

        //6.添加数据。
        shopMapper.add(shop); //添加t_shop表
        Employee employee = shop.getAdmin();
        String salt = RandomUtil.randomString(32);
        String md5psw = SecureUtil.md5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5psw);
        employee.setState(0);
        employee.setShopId(shop.getId());

        Logininfo logininfo = new Logininfo();
        BeanUtil.copyProperties(employee,logininfo); //克隆相同字段属性
        logininfo.setType(0);//0管理员，1用户
        logininfoMapper.add(logininfo); //添加t_logininfo表
        employee.setLogininfoId(logininfo.getId());

        employeeMapper.add(employee);
        shop.setAdminId(employee.getId());//回填adminId
        shopMapper.update(shop);
        return new AjaxResult();
    }

    //店铺审核通过
    @Override
    public AjaxResult auditPass(ShopAuditLog shopAuditLog) {
        //state：1待审核 2审核成功待激活 3激活成功 4驳回
        //一：改状态1->2
        Shop shop = shopMapper.findOne(shopAuditLog.getShopId());
        shopMapper.updateState(shopAuditLog.getShopId(),2);
        //二：添加审核日志
        shopAuditLog.setState(2);
        shopAuditLogMapper.add(shopAuditLog);
        //三：审核成功发送激活邮件
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            //发送复杂邮件的工具类
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("2567209139@qq.com");
            helper.setSubject("店铺激活邮件");
            //true - 能够再内容中编写html标签 - 会解析
            helper.setText("<h1>你的店铺已经注册!!!</h1><img src='"+shop.getLogo()+"' >" +
                    "<a href='http://127.0.0.1:8080/shop/activation/"+shopAuditLog.getShopId()+"'>点击该链接激活</a>",true);
            //添加附件
           //helper.addAttachment("1.jpg",new File("C:\\Users\\CFF\\Pictures\\QQ图片\\1.jpg"));
            //收件人

            Employee employee = employeeMapper.findOne(shop.getAdminId());
            String email = employee.getEmail();//邮箱地址必须时真实存在的
            helper.setTo(email);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
           e.printStackTrace();
        }

        return new AjaxResult();
    }

    //店铺审核驳回
    @Override
    public AjaxResult auditReject(ShopAuditLog shopAuditLog) {
        //state：1待审核 2审核成功待激活 3激活成功 4驳回
        //一：改状态1->2
        Shop shop = shopMapper.findOne(shopAuditLog.getShopId());
        shopMapper.updateState(shopAuditLog.getShopId(),4);
        //二：添加审核日志
        shopAuditLog.setState(4);
        shopAuditLogMapper.add(shopAuditLog);
        //三：审核成功发送激活邮件
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            //发送复杂邮件的工具类
            //true - 能够添加附件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("2567209139@qq.com");
            helper.setSubject("店铺入驻审核失败邮件");
            //true - 能够再内容中编写html标签 - 会解析
            helper.setText("<h1>你的店铺入驻审核失败!!!</h1>" +
                    "<a href='http://127.0.0.1:8081/#/shopRegister'>点击该链接激活重新入驻</a>",true);
            //添加附件
            //helper.addAttachment("1.jpg",new File("C:\\Users\\CFF\\Pictures\\QQ图片\\1.jpg"));
            //收件人
            Employee employee = employeeMapper.findOne(shop.getAdminId());
            String email = employee.getEmail();//邮箱地址必须时真实存在的
            helper.setTo(email);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        return new AjaxResult();
    }

    //在qq邮箱激活店铺
    @Override
    public void activation(Long id, HttpServletResponse response) {
       shopMapper.updateState(id,3);

        response.setContentType("text/html;charset=UTF-8");
        try {
            response.getWriter().print("<h1 style='color:green;'>激活成功!!!3秒后跳转登录页面</h1>" +
                    "<script>\n" +
                    "  window.setTimeout(function () {\n" +
                    "    location.href = 'http://127.0.0.1:8081/#/login'\n" +
                    "  },3000)\n" +
                    "</script>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 柱状图
    @Override
    public List<Shop> columnChart() {
        return shopMapper.columnChart();
    }

    //导入excel数据 批量添加
    @Override
    public void addBatch(List<Shop> shops) {
        shopMapper.addBatch(shops);
    }
}
